<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>30_聊天dom操作</title>
    <link rel="stylesheet" href="./css/basic.css" />
    <style>
      .container {
        width: 100vw;
        height: 100vh;
        background-color: pink;
        box-sizing: border-box;
        padding: 10px;
      }
      .content {
        width: 100%;
        height: 75%;
        background-color: #fff;
      }
      .input {
        width: 100%;
        height: 20%;
        position: relative;
        margin-top: 20px;
      }
      .input textarea {
        width: 100%;
        height: 100%;
        padding: 10px;
        box-sizing: border-box;
        resize: none;
      }
      .input #btnSend {
        position: absolute;
        bottom: 10px;
        right: 10px;
        width: 100px;
        height: 50px;
        font-size: 20px;
        background-color: rgb(32, 32, 255);
        color: #fff;
      }
      .message {
        color: brown;
        font-weight: bolder;
        font-size: 30px;
        margin-right: 20px;
      }
      .datetime {
        color: #000;
        font-size: 12px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="content"></div>
      <div class="input">
        <textarea name="" id="contentArea" rows="5"></textarea>
        <button id="btnSend">发送</button>
      </div>
    </div>
    <script>
      const textareaDom = document.querySelector("#contentArea");
      const btnDom = document.querySelector("#btnSend");
      const contentDom = document.querySelector(".content");
      btnDom.addEventListener("click", (event) => {
        sendMsg();
      });
      enableBtn();
      textareaDom.addEventListener("keydown", (event) => {
        if(event.key === "Enter") {
          sendMsg()
        }
      });

      textareaDom.addEventListener("input", (event) => {
        enableBtn();
      });
      function enableBtn() {
        if(textareaDom.value) {
            // 删除disabled属性
            btnDom.removeAttribute("disabled")
        }else {
            // 加上属性
            btnDom.setAttribute("disabled", true)
        }
      }
      function sendMsg() {
        const content = textareaDom.value;
        // const p = contentDom.createElement("p")
        const p = document.createElement("p");
        p.innerHTML = `<span class='message'>${content}</span><span class='datetime'>${new Date().toLocaleString()}</span>`;
        contentDom.append(p);
        textareaDom.value = "";
      }
    </script>
  </body>
</html>
